<template>
  <div class="slider-container">
    <input :disabled="disabled" type="range" :min="min" :max="max" :step="step" :value="valueRef" @input="change"
      class="slider" :style="{ '--value-percent': ((valueRef - min) / (max - min) * 100) + '%' }" />
    <div class="slider-value" :style="{ 'width': textWidth }" v-if="text">{{ text }}</div>
  </div>
</template>

<script>
export default {
  name: 'a-slider'
}
</script>
<script setup>
import { defineProps, defineEmits, onMounted, ref, watch } from 'vue'
const emit = defineEmits(['update:modelValue', "change"])
const props = defineProps({
  modelValue: {
    type: [Number],
  },
  value: {
    type: [Number],
  },
  text: {
    type: String,
  },
  min: {
    type: Number,
    default: 0
  },
  max: {
    type: Number,
    default: 100
  },
  step: {
    type: Number,
    default: 1
  },
  disabled: {
    type: Boolean,
    default: false
  },
  textWidth: {
    type: String,
  },
  color: {
    type: String,
  }
});


const valueRef = ref(0)
const background = ref('linear-gradient(to right, var(--primary-color) var(--value-percent), var(--card-background-color) var(--value-percent))')

const change = (e) => {
  const newValue = e.target.value
  // 避免重复触发
  if (valueRef.value === newValue) {
    return
  }
  valueRef.value = newValue
  if (props.modelValue) {
    emit('update:modelValue', newValue)
  }
  emit('change', newValue)
}
watch(() => props.modelValue, (newVal) => {
  valueRef.value = props.modelValue
})
watch(() => props.value, (newVal) => {
  valueRef.value = newVal
})
watch(() => props.color, (newVal) => {
  background.value = `linear-gradient(to right, ${newVal} var(--value-percent), var(--card-background-color) var(--value-percent))`
})
onMounted(() => {
  if (props.modelValue) {
    valueRef.value = props.modelValue
  } else if (props.value) {
    valueRef.value = props.value
  }
  if (props.color) {
    background.value = `linear-gradient(to right, ${props.color} var(--value-percent), var(--card-background-color) var(--value-percent))`
  }
});
</script>

<style scoped>
.slider-container {
  width: 100%;
  display: flex;
  align-items: center;
}

.slider {
  border: none;
  flex: 1;
  width: 0;
  height: 6px;
  padding: 0;
  -webkit-appearance: none;
  background: linear-gradient(to right, var(--primary-color) var(--value-percent), var(--card-background-color) var(--value-percent));
  outline: none;
  border-radius: 4px;
}

.slider:hover::-webkit-slider-thumb {
  width: 14px;
  height: 14px;
  background: var(--primary-color-hover);
}

.slider::-webkit-slider-thumb {
  transition: all 0.3s ease;
  -webkit-appearance: none;
  width: 14px;
  height: 14px;
  background: var(--primary-color);
  cursor: pointer;
  border-radius: 50%;
  transform: scale(1);
}

.slider::-webkit-slider-thumb:hover {
  transform: scale(1.2);
}

.slider-value {
  text-align: center;
  font-size: 14px;
  margin-left: 4px;
}
</style>